/**
 * 业务表单基础的增、改
 */
import {getDetail, getFormBuildConfig, add, update, init} from '@/views/youshuda/api/BaseApi'
//表单配置
import {formConf} from "@/views/youshuda/components/FormBuild/generator/config";
import {EventMixins} from "@/views/youshuda/mixins/EventMixins"
import {FromBuildConfigMixins} from "@/views/youshuda/mixins/FromBuildConfigMixins";

export const TableDetailMixins = {
  components: {
    FormItem: () => import('@/views/youshuda/components/FormItem/index'),
    //表单配置展示组件
    DraggableItem: () => import('@/views/youshuda/components/FormBuild/generator/DraggableItem')
  },
  mixins: [EventMixins,FromBuildConfigMixins],
  props: {
    defPk: {
      default: ''
    },
    //处理入口类型：业务表单处理（Form）、流程表单处理（Proc）
    enterType: {
      default: 'Form'
    },
    //表单浏览类型 UPDATE：修改、DETAIL：查看详情
    VisitType: {
      default: ''
    },
    //当前操作请求URL前缀
    visitConfig: {
      type: Object,
      default: () => {
        return {}
      }
    },
    //表单设计Key
    formBuildKey: {
      default: ''
    },
    //是否需要操作按钮
    needOperBtn: {
      default: true
    },
    //当前表单字段信息
    fieldInfo: {
      type: Array,
      default: []
    },
    //表单配置信息
    configParams: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
  },
  data() {
    return {
      // 字段信息
      init: {
        fieldInfo: []
      },
      // 表单参数
      form: {},
      formConfig:{},
      // 标识进入页面是否加载完成
      isLoadFinish: false,
      //表单设计字段配置信息
      formBuildConfig: [],
      //主键字段信息
      pkColumns:{},
      // 标识提交按钮是否可用
      isSubmitForm: false,
      //业务模块生成ID
      tabGenId: '',
      //新增还是编辑
      operType: 'add',
      // 主子表时，关联字段
      foreignKey: '',
      //主表数据
      parentFormData: '',
      // 加载图片
      loading: require('@/assets/images/loading.gif'),

      nowRenderKey: '' //重新渲染组件时唯一标识
    }
  },
  created() {
    //业务模块生成ID
    if (this.strIsEmpty(this.tabGenId)) {
      //提交URL前缀
      if (this.visitConfig == null || this.visitConfig == undefined) {
        console.log("数据组件关联模块配置为空，中止加载...");
        return;
      }
      if (this.visitConfig['genType'] == '2') {
        //优树搭
        this.tabGenId = this.visitConfig['tableId']
      } else {
        //平台标准方式
        this.prefixUrl = this.visitConfig['baseUrlPrefix']
      }
    }
    if (!this.strIsNotEmpty(this.tabGenId) && !this.strIsNotEmpty(this.prefixUrl)) {
      this.msgError("操作失败，当前模块请求地址为空")
      return;
    }
    this.loading = this.loading + '?' + Math.random()
    //获取主子表关联字段
    if (this.configParams && this.configParams['PrimaryFormData']) {
      this.foreignKey = this.configParams['foreignKey']
      //主表关联值
      this.parentFormData = this.configParams['PrimaryFormData'][this.configParams['primaryTableKey']]
      //设置关联值
      this.form[this.foreignKey] = this.parentFormData;
    }
    /** 加载数据 **/
    this.initData()
  },
  /** 当前表单销毁前，事件处理 **/
  beforeDestroy() {
    if(this.formConfig && this.formConfig['formClose']){
      this.evalEventCode(this.formConfig['formClose'])
    }
  },
  methods: {
    /** 获取数据 */
    initData() {
      let that=this
      let _defPk = 'add';
      if (this.strIsNotEmpty(this.defPk)) {
        this.operType = 'edit'
        _defPk = this.defPk;
      } else {
        this.operType = 'add'
      }
      this.reset()
      getDetail(this.tabGenId, this.prefixUrl, _defPk).then(res => {
        if (res.code == 200) {
          let formData = res.data['data']
          //表单数据
          if(formData){
            that.form = {...formData}
          }
          //表单设计字段配置信息
          this.formBuildConfig = this.dealFormBuildConfig(that.form,this.formDataOptions,res.data['formBuildConfig'])
          //主键字段信息
          this.pkColumns = res.data['pkColumns']
          //生成唯一标识，主要考虑用于子表
          if (this.strIsEmpty(this.form['defPk'])) {
            this.form['defPk'] = this.generateUuid()
          }
          this.resetForm('form')
          /** 表单加载完成后，执行表单初始 **/
          this.formConfig = res.data['formConfig'] || formConf
          //表单浏览类型 UPDATE：修改、DETAIL：查看详情
          this.formConfig['VisitType'] = this.VisitType

          this.dealFormLoadFinishEvent()
          // 切换加载效果
          this.closeLoad()
        } else {
          this.msgError(res.msg)
        }
      })

    },
    /** 表单加载完成后，执行表单初始 **/
    dealFormLoadFinishEvent(){
      if(this.formConfig && this.formConfig['formInit']){
        this.evalEventCode(this.formConfig['formInit'])
      }
    },
    closeLoad() {
      var that = this
      // 标记页面已加载完成
      setTimeout(function () {
        that.isLoadFinish = true
      }, 800)
    },
    // 表单重置
    reset() {
      this.init.fieldInfo = JSON.parse(JSON.stringify(this.fieldInfo))
      for(let field of this.init.fieldInfo){
        if(this.strIsNotEmpty(field.columnName)){
          this.$set(field, 'fieldData', null)
            // 表单数据置空
          this.$set(this.form, field.columnName, null)
        }
      }
      //设置关联值
      this.form[this.foreignKey] = this.parentFormData;
      //生成唯一标识，主要考虑用于子表
      if (this.strIsEmpty(this.form['defPk'])) {
        this.form['defPk'] = this.generateUuid()
      }
      this.resetForm('form')
    },
    /** 取消按钮 */
    cancel() {
      this.$emit('cancel')
    },
    /** 校验数据是否通过，并返回 **/
    formData() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$emit('subFormData', {'valid': valid, 'data': this.form})
        } else {
          this.$emit('subFormData', {'valid': valid, 'data': null})
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      //禁用提交按钮
      this.isSubmitForm = true
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          /** 打开遮罩层 **/
          this.openLoading();
          if (this.enterType == 'Form') {
            /**
             * 业务表单处理
             */
            if (this.operType == 'edit') {
              update(this.tabGenId, this.prefixUrl, this.form).then(response => {
                this.msgSuccess('修改成功')
                this.$emit('cancel', {isRef: true})
              }).finally(() => {
                this.isSubmitForm = false
                /** 关闭遮罩层 **/
                this.closeLoading();
              })
            } else {
              add(this.tabGenId, this.prefixUrl, this.form).then(response => {
                this.msgSuccess('新增成功')
                this.$emit('cancel', {isRef: true})
              }).finally(() => {
                this.isSubmitForm = false
                /** 关闭遮罩层 **/
                this.closeLoading();
              })
            }
          } else {
            /**
             * 流程表单处理
             */
            //TODO 流程表单处理

          }
        } else {
          //解除禁用提交按钮
          this.isSubmitForm = false
          /** 关闭遮罩层 **/
          this.closeLoading();
        }
      })
    },

  },
  watch: {
    form: {
      deep: true,
      handler() {
        this.init.fieldInfo.forEach((item, index) => {
          // 表单数据置空
          this.$set(this.init.fieldInfo[index], 'fieldData', this.form[item.columnName])
        })
      }
    }

  }
}
